package com.lanou3g.ptp.api.web.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.lanou3g.ptp.sso.service.SsoService;
import com.lanou3g.ptp.vo.TaskVO;
import com.lanou3g.ptp.base.service.BaseService;
import com.lanou3g.ptp.entity.*;
import com.lanou3g.ptp.signInDate.service.SignInDateService;
import com.lanou3g.ptp.task.service.TaskService;
import com.lanou3g.ptp.teachlink.service.TeachlinkService;
import com.lanou3g.ptp.user.service.UserService;
import com.lanou3g.ptp.taskrole.service.TaskRoleService;
import com.lanou3g.ptp.taskstudent.service.TaskStudentService;
import com.lanou3g.utils.PtpResult;
import com.lanou3g.utils.PtpResultUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;


@Api(description = "任务接口")
@RestController
public class TaskController {
    @Reference
    private TaskService taskService;
    @Reference
    private BaseService baseService;
    @Reference
    private SignInDateService signInDateService;
    @Reference
    private TaskStudentService taskStudentService;
    @Reference
    private TaskRoleService taskRoleService;
    @Reference
    private TeachlinkService teachlinkService;
    @Reference
    private UserService userService;
    @Reference
    private SsoService ssoService;

    @ApiOperation("管理角色通过ID获取任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "任务Id")
    })
    @GetMapping("/task/{id}")
    public PtpResult taskInfo(@PathVariable Long id) {
        try {
            TaskVO taskVO = taskService.findTaskVOById(id);
            Task task = taskVO.getTask();
            ArrayList<TaskRole> taskRoles = taskVO.getTaskRoles();
            ArrayList<Long> taskStudents = taskVO.getTaskStudents();
            Base base = baseService.findById(task.getBaseId());
            Teachlink teachlink = teachlinkService.findById(task.getTeachlinkId());
            User user = userService.userById(task.getBaseTeacherId());
            Map<String, Object> result = new HashMap<>();
            result.put("id", task.getId());
            result.put("name", task.getName());
            result.put("teachlink_mode", teachlink.getMode());
            result.put("description", task.getDescription());
            result.put("base_name", base.getName());
            result.put("teacher_name", user.getName());
            result.put("teachlink_name", teachlink.getName());
            result.put("longitude", task.getLongitude());
            result.put("latitude", task.getLatitude());
            result.put("distribution", task.getDistribution());
            result.put("task_start_time", task.getTaskStartTime());
            result.put("task_end_time", task.getTaskEndTime());
            result.put("address", base.getAddress());
            result.put("taskStudents", taskStudents);
            result.put("taskRoles", taskRoles);
            return PtpResultUtils.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }
    }

    @ApiOperation("管理角色添加任务")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "",value = "")
    })
    @PostMapping("/task")
    public PtpResult newTask(@RequestBody TaskVO taskVO,String token) {
        try {
            taskService.insert1(taskVO,token);
            return PtpResultUtils.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }

    }

    @ApiOperation("管理角色删除一任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "任务Id")
    })
    @DeleteMapping("/task/{id}")
    public PtpResult delete(@PathVariable Long id) {
        try {
            taskService.delete(id);
            return PtpResultUtils.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }

    }

    @ApiOperation("管理角色查询所有")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "页数,默认1"),
            @ApiImplicitParam(name = "keyword",value ="关键字" ),
            @ApiImplicitParam(name = "size",value = "显示条数,默认30")
    })
    @GetMapping("/tasks")
    public PtpResult findAll(@RequestParam(value = "page", defaultValue = "1") Integer page,
                             String keyword,
                             @RequestParam(value = "size", defaultValue = "30") Integer size) {
        try {
            PageInfo<Task> all;
            if (keyword != null && !keyword.trim().equals("")) {
                all = taskService.findByKeyword(page, size, keyword);
            } else {
                all = taskService.findAll(page, size);
            }
            return PtpResultUtils.ok(all);
        } catch (Exception e) {
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }
    }

    @ApiOperation("管理角色批量删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids",value = "任务id数组")
    })
    @DeleteMapping("/tasks/{ids}")
    public PtpResult deletes(@PathVariable Long[] ids) {
        try {
            taskService.deletes(ids);
            return PtpResultUtils.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }

    }

    @ApiOperation("管理角色修改")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "修改的任务id")
    })
    @PutMapping("/task/{id}")
    public PtpResult update(@PathVariable Long id, TaskVO taskVO,String token) {
        try {
            taskService.update(id, taskVO,token);
            return PtpResultUtils.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }
    }

    @ApiOperation("管理员审批")
    @GetMapping("/task/view/{teachlinkId}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "teachlinkId",value = "教学环节的id")
    })
    public PtpResult view(@PathVariable Long teachlinkId){
        try{
            List<Task> all1 = taskService.findAll1(teachlinkId);
            return PtpResultUtils.ok(all1);
        }catch (Exception e){
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }
    }

    @ApiOperation("管理员批量修改成合格任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "taskIds",value = "任务id的数组")
    })
    @PutMapping("/updatesYes/{taskIds}")
    public PtpResult updatesYes(@PathVariable Long[] taskIds,Task task){
        try{
            task.setStatus(0);
            taskService.updates(taskIds,task);
            return PtpResultUtils.ok();
        }catch (Exception e){
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }
    }
    @ApiOperation("管理员批量修改成不合格任务")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "taskIds", value = "任务id数组", paramType = "Integer")
    })
    @PutMapping("/updatesNo/{taskIds}")
    public PtpResult updatesNo(@PathVariable Long[] taskIds,Task task){
        try{
            task.setStatus(4);
            taskService.updates(taskIds,task);
            return PtpResultUtils.ok();
        }catch (Exception e){
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }
    }

    @ApiOperation("学生增加任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "",value = "")
    })
    @PostMapping("/myTask")
    public PtpResult studentInsert(@RequestBody TaskVO taskVO,String token){
        try {
            taskService.insert1(taskVO,token);
            return PtpResultUtils.ok(200);
        }catch (Exception e){
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }
    }
    @ApiOperation("学生修改任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "")
    })
    @PutMapping("/myTask/{id}")
    public PtpResult studentUpdate(@PathVariable Long id,TaskVO taskVO,String token){
        try {
            update(id,taskVO,token);
            return PtpResultUtils.ok(200);
        }catch (Exception e){
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }
    }
    @ApiOperation("学生查看自己所有的任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "用户码")
    })
    @GetMapping("/myTasks")
    public PtpResult studentFind(String token) {
        try {
            Student user = (Student) ssoService.tokenUser(token);
            Long id = user.getId();
            List<TaskStudent> allByStudentId = taskStudentService.findAllByStudentId(id);
            ArrayList<Task> list = new ArrayList<>();
            for (TaskStudent taskStudent : allByStudentId) {
                Long taskId = taskStudent.getTaskId();
                TaskVO taskVO = taskService.findTaskVOById(taskId);
                Task task = taskVO.getTask();
                list.add(task);
            }
            return PtpResultUtils.ok(list);
        } catch (Exception e) {
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }

    }

    @ApiOperation("学生查看任务明细")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "taskId",value = "任务id"),
            @ApiImplicitParam(name = "token",value = "用户码")
    })
    @GetMapping("/myTask/{taskId}")
    public PtpResult studentFind(@PathVariable Long taskId, String token) {
        try {
            Student user = (Student) ssoService.tokenUser(token);
            Long id = user.getId();
            Task task = taskService.findById(taskId);
            Base base = baseService.findById(task.getBaseId());
            Teachlink teachlink = teachlinkService.findById(task.getTeachlinkId());
            User user1 = userService.userById(task.getBaseTeacherId());
            Map<String, Object> result = new HashMap<>();
            result.put("id", task.getId());
            result.put("status",task.getStatus());//进度状态
            result.put("name", task.getName());//任务名
            result.put("teachlink_mode", teachlink.getMode());//实习方式
            result.put("description", task.getDescription());//任务描述
            result.put("base_name", base.getName());//单位名称
            result.put("teacher_name", user1.getName());
            result.put("teachlink_name", teachlink.getName());//辅导老师
            result.put("distribution", task.getDistribution());//报名方式
            result.put("task_start_time", task.getTaskStartTime());//开始时间
            result.put("task_end_time", task.getTaskEndTime());//结束时间
            result.put("address", base.getAddress());//单位地址
            result.put("linkman",base.getContacts());//单位联系人
            result.put("tel",base.getTel());//联系人
            return PtpResultUtils.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }
    }

    @ApiOperation("日志情况")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "taskId",value = "任务id")
    })
    @GetMapping("/diarySituation/{taskId}")
    public PtpResult diarySituation(@PathVariable Long taskId){
        try{
            Map<String, List<Diary>> dateListMap = taskService.diarySituation(taskId);
            return PtpResultUtils.ok(dateListMap);
        }catch (Exception e){
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }
    }
}

